<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="姓名">
          <el-input v-model="formSearch.name">
            <template #suffix>
              <el-icon> </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="登录账号">
          <el-input v-model="formSearch.account">
            <template #suffix>
              <el-icon> </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="员工编号">
          <el-input v-model="formSearch.employeeNumber">
            <template #suffix>
              <el-icon> </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="单位名称">
          <el-input v-model="formSearch.orgName">
            <template #suffix>
              <el-icon> </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="状态">
          <el-select v-model="formSearch.status">
            <el-option label="禁用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleSearch">查 询</el-button>
          <el-button @click="handleSearch">重 置</el-button>
          &nbsp; &nbsp;
          <el-link
            type="primary"
            :underline="false"
            @click="searchInputExpland = !searchInputExpland"
          >
            <template v-if="searchInputExpland">
              收起 &nbsp; <el-icon><arrow-up /></el-icon>
            </template>
            <template v-if="!searchInputExpland">
              展开 &nbsp; <el-icon><arrow-down /></el-icon>
            </template>
          </el-link>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="dataGridAccount"
    show-header="false"
    defaultSort="descending"
    defaultSortBy="name"
    :request="handleLoadGrid"
    @onRowSelectCurrentChange="handleRowSelectCurrentChange"
    @onRowSelectionChange="handleRowSelectionChange"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <el-button size="mini" type="primary" :icon="Plus" @click="handleAdd"
        >新增账号</el-button
      >
      <el-button size="mini" :icon="Edit" @click="handleEdit"
        >重置密码</el-button
      >
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 account 仅在当前作用域有效 -->
    <template #account="slotProps">
      <el-link type="primary" @click="handleView(slotProps.row)">{{
        slotProps.row.account
      }}</el-link>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 status 仅在当前作用域有效 -->
    <template #status="slotProps">
      <el-switch v-model="slotProps.row.status" :active-value="'1'" />
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
    <template #operate="slotProps">
      <el-link type="primary" @click="handleEdit(slotProps.row)">编辑</el-link>
      &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row.accountId)"
        >删除
      </el-link>
    </template>
  </data-grid>

  <edit-form ref="editFormRef" @on-submit="onEditSubmit"></edit-form>
  <view-form
    ref="viewFormRef"
    @on-close="onViewClose"
    title="账号信息"
  ></view-form>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import ViewForm from "./view.vue";
import { get, post } from "../../../utils/request";
import {
  Download,
  Edit,
  Plus,
  Warning,
  ArrowDown,
  ArrowUp,
  Calendar,
  Delete,
} from "@element-plus/icons-vue";
import { h } from "vue";
import { ElMessageBox, Action, ElNotification } from "element-plus";
import utils from "../../../utils/utils";
import apiAccount from "../api/account";
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      field: "accountId",
      type: "selection",
      align: "center",
      width: 55,
    },

    {
      title: "姓名",
      field: "name",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: "登录账号",
      field: "account",
      sortable: true,
      resizable: true,
      tdSlot: "account",
      width: 250,
    },
    {
      title: "员工编号",
      field: "employeeNumber",
      sortable: true,
      resizable: true,
      width: 180,
    },
    {
      title: "单位名称",
      field: "orgName",
      sortable: true,
      resizable: true,
    },
    {
      title: "部门名称",
      field: "deptName",
      sortable: true,
      resizable: true,
    },
    {
      title: "状态",
      field: "status",
      tdSlot: "status",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: "操作",
      field: "goodsId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiAccount
    .queryAccountListing(params)
    .then((respons: any) => {
      if (respons != undefined) {
        data = respons.data;
      }
    })
    .catch((err: any) => {
      console.log("数据处理错误", err);
      utils.errorNotification("数据处理错误" + err);
    });

  // 返回数据给表格组件
  return data;
};

// 表格事件，非必须
const handleRowSelectCurrentChange = (
  currentRow: any | undefined,
  oldCurrentRow: any | undefined
) => {
  // console.log("handleRowSelectCurrentChange", currentRow, oldCurrentRow);
};
// 表格事件，非必须
const handleRowSelectionChange = (rows: any | undefined) => {
  // console.log("handleRowSelectionChange", rows);
};

// 删除操作事件
const handleDelete = (id: any) => {
  console.log(id, typeof id); //正式开发为 string if (typeof id != "number") {
  // 表格按钮触发的情况，默认参数为按钮对象 target
  if (typeof id != "string") {
    // 根据表格使用单行选中还是多行选中，使用不同的方法获取当前选中的表格
    let rows = dataGridRef.value.getCheckRows();
    let row = dataGridRef.value.getCurrentRow();
    if (rows == null || rows.length != 1) {
      ElMessageBox.alert("请选择一条记录", "提示", {
        confirmButtonText: "OK",
        closeOnClickModal: true,
      }).catch(() => {});
      return;
    }

    ElMessageBox.confirm(`确认删除吗? id ${rows[0].goodsId}` + rows[0].goodsId)
      .then(() => {
        let name = rows[0].name;
        handleSearch();
        ElNotification({
          message: h("i", `账号 ${name} 已删除`),
        });
      })
      .catch((err: any) => {
        console.log("删除操作失败", err);
      });
  } else {
    // 从表格每行右侧链接点击触发的情况
    ElMessageBox.confirm(`确认删除吗?`)
      .then(() => {
        let row = dataGridRef.value.getCurrentRow();
        handleSearch();
        ElNotification({
          message: h("i", `账号 ${row.name} 已删除`),
        });
      })
      .catch((err: any) => {
        console.log("删除操作失败", err);
      });
  }
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开编辑页
const handleEdit = (row: any) => {
  editFormRef.value.show(row);
};
// 新增、编辑页确定按钮回调事件
const onEditSubmit = (result: boolean) => {
  handleSearch();
  ElNotification({
    message: h("i", "新增、修改 xx 成功"),
  });
};
// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};
// 详情页关闭事件
const onViewClose = (result: boolean) => {
  handleSearch();
  ElNotification({
    message: h("i", "详情页已关闭，根据业务情况进行后续处理"),
  });
};

// 查询区域表单数据
const formSearch = reactive({
  account: "",
  name: "",
  employeeNumber: "",
  orgName: "",
  deptName: "",
  status: "",
});

// 表单数据
const formEdit = reactive({
  accountId: "",
  account: "",
  name: "",
  gender: 2,
  employeeNumber: "",
  orgName: "",
  orgCode: "",
  deptName: "",
  deptCode: "",
  status: "",
  email: "",
  mobile: "",
  description: "",
  password: "",
  password1: "",
  password2: "",
});

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
</script>
<style></style>
